package com.world.rickcloudendpoint.service.net.tcp.client;

import cn.hutool.json.JSONUtil;
import com.world.rickcloudendpoint.message.NetMessageBody;
import com.world.rickcloudendpoint.message.NetMessageHead;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.log4j.Log4j2;

/**
 * @description: 配置 netty client 消息处理器
 * @author: jlsong
 * @date: 2021/12/07 00:12:22
 * @version: 1.0
 */
@Log4j2
@ChannelHandler.Sharable
public class TransmissionChannelHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("客户端Active .....");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("客户端收到消息: {}", msg.toString());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    public String sendJson(String json) {
        NetMessageBody body = new NetMessageBody();
        body.setBody(json.getBytes());

        NetMessageHead head = new NetMessageHead();
        head.setHead((short) 1);
        head.setCmd((short) 2);
        head.setVersion("2".getBytes()[0]);
        head.setSerial(3);
        head.setLength(body.getBody().length);

        ClientMessage message = new ClientMessage();
        message.setNetMessageHead(head);
        message.setNetMessageBody(body);
        return JSONUtil.toJsonStr(message);
    }
}
